<?php

class Listing_AdminController extends Ac_AdminController
{

    public function dashboardAction()
    {        
        if(!empty($_GET['from']) && !empty($_GET['to']))
		{
			$from = new MongoDate (strtotime($_GET['from']." 00:00:01"));
			$to = new MongoDate (strtotime($_GET['to']." 23:59:59"));
			
			//total ads
			$this->view->num_all_listing      		= Model_Listing::all(array('c_dt' => array('$gte' => $from, '$lte' => $to)))->count();
			//published ads
        	$this->view->num_published_listing      = Model_Listing::all(array('sa' => Model_Listing::STATUS_PUBLISHED, 'c_dt' => array('$gte' => $from, '$lte' => $to)))->count();
        	//unpublished ads
			$this->view->num_unpublished_listing    = Model_Listing::all(array('sa' => Model_Listing::STATUS_DRAFT, 'c_dt' => array('$gte' => $from, '$lte' => $to)))->count();
			//deleted ads
	        $this->view->num_deleted_listing        = Model_Listing::all(array('sa' => Model_Listing::STATUS_DELETED, 'c_dt' => array('$gte' => $from, '$lte' => $to)))->count();
	        //sold ads
	        $this->view->num_sold_listing           = Model_Listing::all(array('sa' => Model_Listing::STATUS_MARK_SOLD, 'c_dt' => array('$gte' => $from, '$lte' => $to)))->count();
        	//organic ads
			$this->view->num_organic_listing    	= Model_Listing::all(array('$or' => array(array('sa' => Model_Listing::STATUS_PUBLISHED), array('sa' => Model_Listing::STATUS_MARK_SOLD)), 'pv' => array('$exists' => false), 'c_dt' => array('$gte' => $from, '$lte' => $to)))->count();
			//non-organic ads
			$this->view->num_nonorganic_listing    	= Model_Listing::all(array('$or' => array(array('sa' => Model_Listing::STATUS_PUBLISHED), array('sa' => Model_Listing::STATUS_MARK_SOLD)), 'pv' => array('$exists' => true), 'c_dt' => array('$gte' => $from, '$lte' => $to)))->count();
		}else{
			//total ads
			$this->view->num_all_listing      		= Model_Listing::all()->count();
			//published ads
        	$this->view->num_published_listing      = Model_Listing::all(array('sa' => Model_Listing::STATUS_PUBLISHED))->count();
        	//unpublished ads
			$this->view->num_unpublished_listing    = Model_Listing::all(array('sa' => Model_Listing::STATUS_DRAFT))->count();
			//deleted ads
	        $this->view->num_deleted_listing        = Model_Listing::all(array('sa' => Model_Listing::STATUS_DELETED))->count();
	        //sold ads
	        $this->view->num_sold_listing           = Model_Listing::all(array('sa' => Model_Listing::STATUS_MARK_SOLD))->count();
			//organic ads
			$this->view->num_organic_listing    	= Model_Listing::all(array('$or' => array(array('sa' => Model_Listing::STATUS_PUBLISHED), array('sa' => Model_Listing::STATUS_MARK_SOLD)), 'pv' => array('$exists' => false)))->count();
			//non-organic ads
			$this->view->num_nonorganic_listing    	= Model_Listing::all(array('$or' => array(array('sa' => Model_Listing::STATUS_PUBLISHED), array('sa' => Model_Listing::STATUS_MARK_SOLD)), 'pv' => array('$exists' => true)))->count();
			
		}
    }

    public function menuAction()
    {
        $this->view->index = $this->_getParam('index');
    }

    public function indexAction() 
    {
        $this->listAction();
    }
    
    public function listAction() 
    {
        $solr = Ac_Search::getClient();

        $_GET['sort'] = $sort      = !empty($_GET['sort']) ? $_GET['sort'] : 'recent';
        $page      = !empty($_GET['page']) ? $_GET['page'] : 1;
        $per_page  = 30;
        
        
        $this->processRefineSearchForm($page, $per_page, $sort, $query, $fields, $additionalParameters);
        
        $query = '';
        
		if(!empty($_GET['from']) && !empty($_GET['to']))
		{
			$query .= " +posted_at:[".$_GET['from']."T00:00:01Z TO ".$_GET['to']."T23:59:59Z]";
		}
		
        if (!empty($_GET['listing'])) {
            $query .= ' +title:'.$_GET['listing'].' +type_obj_s:Model_Listing';
        }
        else {
            $query .= ' +type_obj_s:Model_Listing';
        }
        
        $start = ($page-1) * $per_page;
        $list = $solr->search($query, $start, $per_page, $additionalParameters);

        //$this->view->list    = Model_Listing::all()->limit(50);
        $this->view->list           = $list->response->docs;
        $this->view->listing_number = $list->response->numFound;
        $this->view->page           = $page;
        $this->view->per_page       = $per_page;
        $this->render('list');
    }
    
    public function editAction()
    {
        /*
        $key    = $_POST['id'];
        $value  = $_POST['val'];
        $locale = $_POST['loc'];
        Model_Translate::addTranslation($key, $value, $locale);
         * 
         */
        echo 'ok';exit;
    }

    public function displayAction()
    {
        $listing = Model_Listing::find($_GET['id']);
        $this->view->listing = $listing;
        $this->view->level1 = Model_Category::getLevel1(array('status'=>Model_Category::STATUS_ACTIVE))->sort(array('pos'=>1));
        $this->render('display');
    }

    public function unpublishAction()
    {
        $listing = Model_Listing::find($_GET['id']);
        $listing->status = Model_Listing::STATUS_DRAFT;
        $listing->save();
        $this->_redirect($this->view->geturl('display','listing', null, 'admin1', array('id'=> $_GET['id'])));
    }

    public function publishAction()
    {
        $listing = Model_Listing::find($_GET['id']);
        $listing->status = Model_Listing::STATUS_PUBLISHED;
        $listing->save();
        $this->_redirect($this->view->geturl('display','listing', null, 'admin1', array('id'=> $_GET['id'])));
    }

    public function deleteAction()
    {
        $listing = Model_Listing::find($_GET['id']);
        $listing->status = Model_Listing::STATUS_DELETED;
        $listing->save();
        $this->_redirect($this->view->geturl('display','listing', null, 'admin1', array('id'=> $_GET['id'])));
    }

    private function processRefineSearchForm($page, $per_page, $sort, &$query, &$fields, &$additionalParameters)
    {
        $results = false;

        $values     = array();
        $valuesplus = array();
        $get     = $_GET;

        if (!empty($_GET['keyword'])) {
            $values['firstname'] = strtolower(trim($_GET['keyword']));
            $values['lastname']       = strtolower(trim($_GET['keyword']));
            $values['username']       = strtolower(trim($_GET['keyword']));
        }

        foreach($values as $k => $val) {
          $values[$k] = ' '.$k.':'.$val.' ';
        }

        if (!empty($values)) {
            $query = implode(' ', $values);
        }

        if (empty($query)) {
            $query = '*:*';
        }

        switch ($_GET['sort']) {
            case 'rel':
                $sort = 'score desc';
                break;
            case 'recent':
                $sort = 'posted_at desc';
                break;
            case 'status':
                $sort = 'status desc';
                break;
            case 'title':
                $sort = 'title asc';
                break;
            default:
                $_GET['sort'] = 'recent';
                $sort         = 'posted_at desc';
        }

        $additionalParameters = array(
            'fl'   => '*,score',
            'sort' => $sort,
        );

        $fq                     = '';
        
        if (!empty($valuesplus)) {
            $fq .= implode(' ', $valuesplus);
        }

        if (!empty($fq)) {
            $additionalParameters['fq'] = $fq;
        }
        
    }
    
    
    public function getCategoryListAction($parent = null) {
        $list = null;
        if ($parent == null) {
            if (!empty($_GET['val'])) {
                $parent = $_GET['val'];
            }
        }
        
        
        if ($parent !== null) {
            $par = Model_Category::find($parent);
            if(!empty($par)) {
                $tmp = $par->getChildren();
            } else {
                $tmp = Model_Category::getLevel1();
            }
        } else {
            $tmp = Model_Category::getLevel1();
        }
        
        foreach($tmp  as $k => $v) {
            $list[] = array('_id' => (string)$v->_id, 'name' => $v->name);
        }
        
        $this->_helper->json(array('list' => $list));
    }
    
    public function updateCategoryAction() {
        
        $id    = $_POST['id'];
        $arr   = array();
        $i     = 0;
        $res = '';
        
        foreach($_POST['level1'] as $i => $idc) {
            $level1 = $_POST['level1'][$i];
            $level2 = $_POST['level2'][$i];
            $level3 = !empty($_POST['level3'][$i]) ? $_POST['level3'][$i] : null;

            $obj = Model_Listing::find($id);

            if (!empty($level3)) {
                $arr[] = new MongoId($level3);
                $obj->ca = $arr;
                //print_r($arr);
                $obj->save();
                if ($res == '') {
                    $res = 'ok';
                }
            } elseif (!empty($level2)) {
                $arr[] = new MongoId($level2);
                $obj->ca = $arr;
                //print_r($arr);
                $obj->save();
                if ($res == '') {
                    $res = 'ok';
                }
            }
            $i++;
        }
        if (empty($res)) {
            $res = 'nok';
        }
        echo $res;
        exit;
    }
}
